<?php
namespace app\staff\model;
use app\common\model\Common;
use think\Request;
use think\Db;
class AdminRank extends Common
{
	protected $table = 'mps_admin';
	protected $append = ['sex_text','admin_type_text','shop_name','g_title'];

	/**
	* 员工销售排行榜
	*/
	public function saleRank($adminWhere, $orderWhere, $order, $page, $row)
	{
		$orderNUmSql = $this->orderNUmSql($orderWhere);
		$orderMoneySql = $this->orderMoneySql($orderWhere);
		return $this->alias('admin')
		->join($orderNUmSql,'admin.admin_id = onum.admin_id','LEFT')
		->join($orderMoneySql,'admin.admin_id = omoney.admin_id','LEFT')
		->field('admin.*,ifnull(onum.order_num,0) as order_num,ifnull(omoney.goods_money,0) as goods_money,ifnull(omoney.profit_money,0) as profit_money,ifnull(omoney.profit_t_money,0) as profit_t_money,ifnull(omoney.turnover_t_money,0) as turnover_t_money')
		->where($adminWhere)->order($order)->page($page, $row)->group('admin.admin_id')
		->select();
	}
	/**
	* 员工排行榜总数
	*/
	public function saleRankCount($adminWhere)
	{
		return $this->alias('admin')->where($adminWhere)->count();
	}
	/**
	* 获取器
	*/
	public function getSexTextAttr($value, $data)
	{
		switch($data['sex']){
			case 0: return '保密';break;
			case 1: return '男';break;
			case 2: return '女';break;
			default: return '异常';break;
		}
	}
	public function getAdminTypeTextAttr($value, $data)
	{
		switch($data['admin_type']){
			case 0: return '总部';break;
			case 1: return '店长';break;
			case 2: return '营业员';break;
			case 3: return '维修员';break;
			default: return '异常';break;
		}
	}
	public function getAddtimeAttr($value)
	{
		return $this->date_time($value);
	}
	public function getShopNameAttr($value, $data)
	{
		return Db::name('shop')->where('shop_id',$data['shop_id'])->value('shop_name');
	}
	public function getGTitleAttr($value, $data)
	{
		return Db::name('access')->alias('a')->join('mps_group g','a.agid = g.agid','RIGHT')->where('a.admin_id',$data['admin_id'])->value('title');
	}
	/***************************** 私有 ******************************/
	/**
	* 订单数
	*/
	private function orderNUmSql($orderWhere)
	{
		$sql = Db::name('order')->alias('order')->field('count(order_id) as order_num,admin_id')->where($orderWhere)->group('admin_id')->select(false);
		return "($sql) as onum";
	}
	/**
	* 销售所有金额统计
	* 销售总额 goods_money
	* 销售总盈利 profit_money
	* 盈利提成 profit_t_money
	* 营业额提成 turnover_t_money
	*/
	private function orderMoneySql($orderWhere)
	{
		$sql = Db::name('orderGoods')->alias('goods')
		->field('sum(goods.goods_money) as goods_money,sum(goods.profit_money) as profit_money,sum(goods.profit_t_money) as profit_t_money,sum(goods.turnover_t_money) as turnover_t_money,order.admin_id')
		->join('mps_order order','order.order_id = goods.order_id','LEFT')
		->where($orderWhere)->group('order.admin_id')->select(false);
		return "($sql) as omoney";
	}
}